/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.common.template;

import com.apache.uct.common.ToolsUtil;
import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;

import java.util.List;

/**
 * description:  格式化Long类型时间
 *
 * @author 创建时间：2016-9-22
 */
public class UpperFirstMethod implements TemplateMethodModel {

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     *
     * @see freemarker.template.TemplateMethodModel#exec(java.util.List)
     */
    public Object exec(List arguments) throws TemplateModelException {
        String str = String.valueOf(arguments.get(0));
        if (ToolsUtil.isNotNull(str)) {
            if (arguments.size() > 1) {
                return toLowerFirst(str);
            } else {
                return toUpperFirst(str);
            }
        }
        return "";
    }

    /**
     * 首字母小写
     *
     * @param str
     * @return
     */
    private String toLowerFirst(String str) {
        if (ToolsUtil.isNull(str))
            return "";
        StringBuffer sb = new StringBuffer();
        sb.append(str.substring(0, 1).toLowerCase() + str.substring(1));
        return sb.toString();
    }

    /**
     * 首字母大写
     *
     * @param str
     * @return
     */
    private String toUpperFirst(String str) {
        if (ToolsUtil.isNull(str))
            return "";
        String names[] = str.split("_");
        StringBuffer sb = new StringBuffer();
        if (names.length < 2) {
            sb.append(names[0].substring(0, 1).toUpperCase() + names[0].substring(1));
        } else {
            for (int i = 0; i < names.length; i++) {
                sb.append(names[i].substring(0, 1).toUpperCase() + names[i].substring(1));
            }
        }
        return sb.toString();
    }
}
